import 'dart:convert';
import 'package:flutter_image_picker/url.dart';
import 'package:flutter_nb_net/flutter_net.dart';

import '../model/http_result.dart';
import '../model/upload_history_result.dart';

/// 成功回调
typedef SuccessListener<T> = Function(T result);

/// 失败回调
typedef FailListener = Function(String msg, int code);

/// 上传相关接口方法
class UploadRepository {
  /// 获取上传历史列表
  static void getUploadHistoryList(
      SuccessListener<UploadHistoryResult> onSuccess,
      FailListener? onFail) async {
    var response = await get(Url.uploadHistoryList);
    response.when(success: (dynamic resp) {
      Map<String, dynamic> map;
      // 如果返回的是未解析的json字符串，则先解析
      if (resp is String) {
        map = jsonDecode(resp);
      } else {
        // 如果能自动解析，则直接使用
        map = resp;
      }
      final model = UploadHistoryResult.fromJson(map);
      onSuccess(model);
    }, failure: (String msg, int code) {
      if (msg.isEmpty) {
        msg = "服务器异常";
      }
      if (onFail != null) {
        onFail(msg, code);
      }
    });
  }

  /// 删除指定上传记录
  static deleteUploadHistory(String id, SuccessListener<HttpResult> onSuccess,
      FailListener? onFail) async {
    var response = await post<HttpResult, HttpResult>(Url.deleteById,
        queryParameters: {
          "id": id,
        },
        decodeType: HttpResult());
    response.when(success: (model) {
      onSuccess(model);
    }, failure: (String msg, int code) {
      if (onFail != null) {
        onFail(msg, code);
      }
    });
  }
}
